//
//  UrlIconNode.cpp
//  client
//
//  Created by ming on 2018/10/29.
//

#include "UrlIconWidget.hpp"
#include "network/HttpClient.h"
#include "Gif/GifUtils.h"
#include "Gif/InstantGif.h"
UrlIconWidget* UrlIconWidget::create()
{
    UrlIconWidget* widget = new (std::nothrow) UrlIconWidget();
    if (widget && widget->init())
    {
        widget->autorelease();
        return widget;
    }
    CC_SAFE_DELETE(widget);
    return nullptr;
}

UrlIconWidget::UrlIconWidget():ui::Widget(){
    _handler = 0;
    _gif = nullptr;
    _imageView = nullptr;
    
}
UrlIconWidget::~UrlIconWidget(){
    
    cancelLuaScriptCallback();
}

void UrlIconWidget::loadFromUrl(const char * url, const char * cachePath){
    _cachePath = cachePath; //FileUtils::getInstance()->fullPathForFilename(cacheName);
    _url = url;
    if (FileUtils::getInstance()->isFileExist(_cachePath)){
        _onDownLoadSucceed();
    }else{
        network::HttpRequest* request = new (std::nothrow) network::HttpRequest();
        request->setUrl(_url);
        request->setRequestType(network::HttpRequest::Type::GET);
        request->setResponseCallback(this, httpresponse_selector(UrlIconWidget::_onHttpResponse));
        network::HttpClient::getInstance()->sendImmediate(request);
        request->release();
    }
}

void UrlIconWidget::_onHttpResponse(cocos2d::network::HttpClient *sender, cocos2d::network::HttpResponse *response){
    if (!response->isSucceed())
    {
        CCLOG("Receive Error! %s\n",response->getErrorBuffer());
        _runLuaCallBack(false);
        return ;
    }
    std::vector<char> *buffer = response->getResponseData();
    CCLOG("path: %s",_cachePath.c_str());
    std::string bufffff(buffer->begin(),buffer->end());
    FILE *fp = fopen(_cachePath.c_str(), "wb");
    if(fp){
        fwrite(bufffff.c_str(), 1,buffer->size(),fp);
        fclose(fp);
        _onDownLoadSucceed();
        _runLuaCallBack(true);
    }else{
        _runLuaCallBack(false);
    }
}

void UrlIconWidget::setLuaScriptCallback(LUA_FUNCTION handler){
    _handler = handler;
}

void UrlIconWidget::cancelLuaScriptCallback(){
    if (_handler > 0){
        LuaEngine * luaEngine = (LuaEngine *)ScriptEngineManager::getInstance()->getScriptEngine();
        luaEngine->removeScriptHandler(_handler);
        _handler = 0;
    }
}

void UrlIconWidget::_runLuaCallBack(bool trueOrFalse){
    if (_handler > 0){
        LuaEngine * luaEngine = (LuaEngine *)ScriptEngineManager::getInstance()->getScriptEngine();
        LuaStack * stack = luaEngine->getLuaStack();
        if (stack){
            stack->pushBoolean(trueOrFalse);
            stack->executeFunctionByHandler(_handler, 1);
        }
        luaEngine->removeScriptHandler(_handler);
        _handler = 0;
    }
}

void UrlIconWidget::_onDownLoadSucceed(){
    bool isGif = GifUtils::isGif(_cachePath.c_str());
    removeAllProtectedChildren();
    _gif = nullptr;
    _imageView = nullptr;
    
    if(isGif){
        _gif = InstantGif::create( _cachePath.c_str() );
        if(_gif){
            addProtectedChild(_gif);
        }
    }else{
        _imageView = ui::ImageView::create(_cachePath);
        if (_imageView){
            addProtectedChild(_imageView);
        }
    }
}

Node * UrlIconWidget::getVirtualRenderer(){
    if(_gif != nullptr){
        return _gif;
    }
    if(_imageView != nullptr){
        return _imageView;
    }
    return nullptr;
}


